package com.hs.srm.admin.modules.inforecord.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.inforecord.VO.SupplyGoodVO;
import com.hs.srm.admin.modules.inforecord.entity.SupplyGoodEntity;
import com.hs.srm.admin.modules.inforecord.service.SupplyGoodService;
import com.hs.srm.admin.modules.sequence.service.SequenceService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.DictDataUtil;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysDictService;
import com.hs.srm.common.utils.Constants;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.sap.conn.jco.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author socik
 * @date 2019/6/13 13:20
 * @email socik@qq.com
 */
@RestController
@RequestMapping("/supplyGood")
public class SupplyGoodController extends AbstractController {

    @Autowired
    private SupplyGoodService supplyGoodService;

    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private SysDictService sysDictService;

    /**
     * @Description: 查询列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils pu = this.supplyGoodService.queryPage(params);
        List<SupplyGoodEntity> list = (List<SupplyGoodEntity>) pu.getList();
        list = EntityUtils.valToTxt(list);
        pu.setList(list);
        return R.ok(pu);
    }

    /**
     * @Description 删除物料信息
     * @Param [pkId]
     * @Return org.springframework.web.servlet.ModelAndView
     * @Author socik
     * @Date 2019/5/23 11:37
     */
    @SysLog("删除物料信息")
    @RequestMapping("/delete")
    public R toDelete(@RequestParam(value = "userIds[]") String[] userIds) {
        boolean flag = this.supplyGoodService.deleteBatchIds(Arrays.asList(userIds));
        if (flag) {
            return R.ok();
        }
        return R.error("删除失败");
    }


    /**
     * @Description sap同步货源记录
     * @Param [inquiryQuotationEntity]
     * @Return java.lang.String
     * @Author socik
     * @Date 2019/6/14 14:19
     */
    public String sendToSapSupply(SupplyGoodEntity supplyGoodEntity, String kz) {

        JCoDestination destination = null;
        JCoFunction function = null;
        JCoParameterList list = null;
        JCoParameterList returnlist = null;
        JCoParameterList tables = null;
        try {
            destination = JCoDestinationManager.getDestination("IDOC_AFS");
            function = destination.getRepository().getFunction("ZFM_SRM_DIRECT_SOURCE_LIST");
            list = function.getImportParameterList();
            returnlist = function.getExportParameterList();
            tables = function.getTableParameterList();
        } catch (JCoException e) {
            e.printStackTrace();
        }
        //获取Sap导入参数接口
        list.setValue("I_MATNR", "0000000000" + supplyGoodEntity.getMaterialCode());
        list.setValue("I_WERKS", supplyGoodEntity.getWerks());
        JCoTable ImportTable = tables.getTable("T_EORD");
        JCoTable ImportTable1 = tables.getTable("T_EORDX");
        ImportTable.appendRow();
        ImportTable1.appendRow();
        //新增
        if (kz.equals("I")) {
            //创建人
            ImportTable.setValue("ERNAM", supplyGoodEntity.getCreateBy());
            //创建时间
            ImportTable.setValue("ERDAT", DateUtils.format(DateUtils.currentDateTime(), DateUtils.DATE_TIME_ALL_SAP));
        } else {
            ImportTable.setValue("ERDAT", DateUtils.format(DateUtils.currentDateTime(), DateUtils.DATE_TIME_ALL_SAP));
            //货源记录编号
            ImportTable.setValue("ZEORD", String.format("%05d", supplyGoodEntity.getSupplyNum()));
            //货源记录编号
            ImportTable1.setValue("ZEORD", String.format("%05d", supplyGoodEntity.getSupplyNum()));
            //工厂
            ImportTable1.setValue("WERKS", supplyGoodEntity.getWerks());
            //物料号
            ImportTable1.setValue("MATNR", "0000000000" + supplyGoodEntity.getMaterialCode());
            //有效日期开始
            ImportTable1.setValue("VDATU", "X");
            if (supplyGoodEntity.getOldEndData() != supplyGoodEntity.getPriceEndData()) {
                //有效日期结束
                ImportTable1.setValue("BDATU", "X");
            }

        }
        //默认字段
        ImportTable.setValue("EORTP", 0);
        //采购组织,国内的全部是1000， 1700,1800都是1400
        if (supplyGoodEntity.getWerks().equals("1700") || supplyGoodEntity.getWerks().equals("1800")) {
            ImportTable.setValue("EKORG", "1400");
        } else {
            ImportTable.setValue("EKORG", "1000");
        }
        //供应商代码
        ImportTable.setValue("LIFNR", String.format("%010d", Integer.valueOf(supplyGoodEntity.getSrmCode())));
        //物料号
        ImportTable.setValue("MATNR", "0000000000" + supplyGoodEntity.getMaterialCode());
        //没有货源记录编号，新增一个
        if (supplyGoodEntity.getSupplyNum() == null) {
            kz = "I";
            //同步，避免并发造成货源记录编号重复
            synchronized (this) {
                supplyGoodEntity.setSupplyNum(sequenceService.getNextVal("supplyNum"));
                supplyGoodService.updateById(supplyGoodEntity);
            }
        }
        //工厂
        ImportTable.setValue("WERKS", supplyGoodEntity.getWerks());
        //有效日期开始
        ImportTable.setValue("VDATU", DateUtils.format(supplyGoodEntity.getStartData(), DateUtils.DATE_TIME_ALL_SAP));
        //有效日期结束
        ImportTable.setValue("BDATU", DateUtils.format(supplyGoodEntity.getPriceEndData(), DateUtils.DATE_TIME_ALL_SAP));
        //标记.I 新增；U 修改
        ImportTable.setValue("KZ", kz);
        //采购物料的工厂,公司间需要，外面公司不需要这个字段
        if (sysDictService.getValByType(DictDataUtil.DictType.GC).contains(supplyGoodEntity.getSrmCode())) {
            ImportTable.setValue("RESWK", supplyGoodEntity.getSrmCode());
        }
        try {
            function.execute(destination);
        } catch (JCoException e) {
            e.printStackTrace();
        }
        String returnMsg = (String) returnlist.getValue("E_MESSAGE");
        Integer supplyNum = Integer.valueOf((String) ImportTable.getValue("ZEORD"));
        supplyGoodEntity.setSupplyNum(supplyNum);
        if ("SUCCESS".equals(returnMsg)) {
            return "S";
        }
        return returnMsg;
    }

    /**
     * @Description 跳转到新增页面获取登陆用户名
     * @Param []
     * @Return org.springframework.web.servlet.ModelAndView
     * @Author socik
     * @Date 2019/5/27 11:55
     */

    @RequestMapping("/toAdd")
    public ModelAndView toAdd() {
        // 把查询出来的对象赋值给物料信息实体
        ModelAndView modelAndView = new ModelAndView("modules/inforecord/supply_good_add");
        return modelAndView;
    }

    /**
     * @Description 新增货源
     * @Param []
     * @Author socik
     * @Date 2019/5/27 11:55
     */
    @SysLog("新增货源")
    @RequestMapping("/save")
    public R save(SupplyGoodEntity supplyGoodEntity) {
        SysUserEntity username = this.getUser();
        String werks = supplyGoodEntity.getWerks();
        String[] factoryList = werks.split(",");

        //遍历所有工厂
        for (int i = 0; i < factoryList.length; i++) {
            supplyGoodEntity.setMaterialCode(supplyGoodEntity.getMaterialCode().trim());
            supplyGoodEntity.setSrmCode(supplyGoodEntity.getSrmCode().trim());
            supplyGoodEntity.setCreateBy(username.getUsername());
            supplyGoodEntity.setPurchArg("1000");
            supplyGoodEntity.setCreatetime(DateUtils.currentDateTime());
            supplyGoodEntity.setToSendSap(0);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = "9999-12-31";
            Date date = new Date();
            try {
                date = dateFormat.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            supplyGoodEntity.setPriceEndData(date);
            //查询货源记录重是否有重复
            SupplyGoodEntity goodEntity = this.supplyGoodService.selectByCode(supplyGoodEntity.getMaterialCode(), supplyGoodEntity.getSrmCode(), factoryList[i]);
            if (goodEntity == null) {
                supplyGoodEntity.setWerks(factoryList[i]);
                //同步，避免并发造成货源记录编号重复
                synchronized (this) {
                    //supplyGoodEntity.setSupplyNum(sequenceService.getNextVal("supplyNum"));
                    supplyGoodEntity.setPkId(null);
                    this.supplyGoodService.insert(supplyGoodEntity);
                }
            }
        }
        return R.ok();
    }


    /**
     * @Description: 货源记录列表
     */
    @RequestMapping("/vendorFromSupplyGoodsList")
    public R vendorFromSupplyGoodsList(@RequestParam Map<String, Object> params) {
        PageUtils pu = this.supplyGoodService.vendorFromSupplyGoods(params);
        List<SupplyGoodVO> list = (List<SupplyGoodVO>) pu.getList();
        list = EntityUtils.valToTxt(list);
        pu.setList(list);
        return R.ok(pu);
    }

    @SysLog("货源记录确认")
    @RequestMapping("/confirmInfo/{pkId}")
    public R confirmInfo(@PathVariable("pkId") String[] pkId) {
        List<SupplyGoodEntity> supplyGoodEntityList = this.supplyGoodService.selectBatchIds(Arrays.asList(pkId));
        for (SupplyGoodEntity supplyGoodEntity : supplyGoodEntityList) {
            String flg = this.sendToSapSupply(supplyGoodEntity, "I");
            if (flg.equals("S")) {
                supplyGoodEntity.setInfoStatus(1);
                supplyGoodEntity.setToSendSap(1);
                this.supplyGoodService.updateById(supplyGoodEntity);
            } else {
                return R.error(flg);
            }
        }
        return R.msg("同步成功！");
    }

    /**
     * 获取未确认的货源记录数
     * supplyGoods:confirmInfo:拥有该权限的用户才可访问
     */
    @GetMapping("/getConfirmCount")
    @RequiresPermissions("supplyGoods:confirmInfo")
    public R getConfirmCount() {
        //查找未确认的信息记录数
        // info_status：信息记录状态：0，未确认；1，已确认S
        int count = supplyGoodService.selectCount(new EntityWrapper<SupplyGoodEntity>()
                .eq("info_status", 0));
        return R.ok(count);
    }

    /**
     * 编辑未确认的货源记录订单
     */
    @RequestMapping("/toEdit")
    public ModelAndView declarationDetails(@RequestParam("pkId") String pkId) {
        ModelAndView modelAndView = new ModelAndView("modules/inforecord/supply_good_edit");
        SupplyGoodEntity supplyGoodEntity = supplyGoodService.selectById(pkId);
        modelAndView.addObject("qualityEntity", supplyGoodEntity);
        return modelAndView;
    }

    /**
     * 编辑货源记录
     *
     * @param supplyGoodEntity
     * @return
     */
    @SysLog("编辑货源记录")
    @PostMapping("/edit")
    public R edit(SupplyGoodEntity supplyGoodEntity) {
        SupplyGoodEntity sg = supplyGoodService.selectById(supplyGoodEntity.getPkId());
        String time = "9999-12-31";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = dateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        sg.setPriceEndData(date);
        //修改的开始时间、结束时间存入要保存的entity
        sg.setStartData(supplyGoodEntity.getStartData());
        //同步SAP，修改数据
        String flg = sendToSapSupply(sg, "U");
        if (flg.equals("S")) {
            supplyGoodService.updateById(sg);
        } else {
            return R.error(flg);
        }
        return R.ok();
    }

    /**
     * 用Excel批量导入供应商的信息
     */
    @SysLog("导入货源记录的信息")
    @RequestMapping("/imp")
    // @RequiresPermissions("vendor:imp")
    public R impXls(@RequestParam("xlsFile") MultipartFile xlsFile) {
        File baseDir = new File(SysConfig.getUploadPath());
        if (!baseDir.exists() || !baseDir.isDirectory()) {
            baseDir.mkdirs();
        }
        String path = SysConfig.getUploadPath() + File.separator + System.currentTimeMillis()
                + xlsFile.getOriginalFilename();
        File savedFile = new File(path);
        try {
            xlsFile.transferTo(savedFile);
        } catch (Exception ex) {
            return R.error(Constants.ImpResultMsg.UPLOAD_FILE_FAILURE);
        }
        try {
            Map<String, Object> errorMsg = this.supplyGoodService.importData(savedFile, this.getUser().getUsername());
            if (errorMsg.isEmpty()) {
                return R.ok();
            }
            return (errorMsg.get("err") == null) ? R.error() : R.error(errorMsg.get("err").toString());
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error(Constants.ImpResultMsg.IMPORT_DATA_FAILURE);
        } finally {
            savedFile.delete();// 导入完成后不管是否成功，都将文件删除
        }
    }


    /**
     * 保存用Excel批量导入信息记录
     */
    @SysLog("导入信息信息记录")
    @RequestMapping("/saveImp")
    // @RequiresPermissions("vendor:imp")
    public R saveImp() {
        int impCount = this.supplyGoodService.saveImp();
        return R.ok().put("impCount", Integer.valueOf(impCount));
    }
}
